package com.framework.loippi.service.weixin.impl;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import com.framework.loippi.cache.ConfigCache;
import net.sf.json.JSONObject;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.dom4j.Element;
import org.springframework.stereotype.Service;

import com.framework.loippi.entity.weixin.WxUserJson;
import com.framework.loippi.service.weixin.WxBaseService;
import com.google.gson.Gson;


@Service("wxBaseService")
public class WxBaseServiceImpl implements WxBaseService {


	/**
	 * 微信公共号获取的ACCESS_TOKEN，定时任务自动获取，每一个半小时更新一次
	 */
	public static String ACCESS_TOKEN = "";
	
	/**
	 * JS接口的使用ticket
	 */
	public static String JSAPI_TICKET= "";
	
	public final static String QRSCENETICKET_URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=";

	/**
	 * 小程序
	 */
	public final static String ACCESSTOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

	/**
	 * 公众号
	 */
	public final static String ACCESSTOKEN_URL_FOR_PUBLIC = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

	public final static String DOWNMEDIA_URL = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
	
	public final static String INITMENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

	public final static String GETMENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";
	
	public final static String DELMENU_URL = "https：//api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";



	//公众号授权登录
	public final  String USERACCESSTOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=CODE&grant_type=authorization_code";
	
	//小程序授权扥估了
	public final  String APPLETACCESSTOKEN_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=CODE&grant_type=authorization_code";
	
	public final static String GETUSER_URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID";
	
	public final static String GETUSERBATCH_URL = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=ACCESS_TOKEN";
	
	public final static String GETUSERLIST_URL = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID";
	
	public final static String JSAPI_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
	
	public final static String JS_STR = "jsapi_ticket=JSAPI_TICKET&noncestr=NONCESTR&timestamp=TIMESTAMP&url=URL";
	
	public final static String TEMPLATEMSG_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
	
	public final static String USER_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	
	public static String FILEDIR = "./";
	
	
	/* (non-Javadoc)
	 * @see com.yykj.service.WxBaseService#handleMessage(org.dom4j.Element)
	 */
	@Override
	public String handleMessage(Element root) {
		// TODO Auto-generated method stub
		return null;
	}
	
	/**
	 * 获取微信公共号AccessToken，并存贮于静态变量ACCESS_TOKEN
	 * @return
	 */
	@SuppressWarnings("static-access")
	public String getAccessToken(){
		String result= null;
		HttpClient client = new HttpClient();
		HttpMethod method=new GetMethod(String.format(ACCESSTOKEN_URL,ConfigCache.getConfig("wx.ma.appId"),ConfigCache.getConfig("wx.ma.secret")));
		try {
			client.executeMethod(method);
			result = method.getResponseBodyAsString();
			method.releaseConnection();
			
			JSONObject jsonob = JSONObject.fromObject(result);
			result = jsonob.getString("access_token");
			ACCESS_TOKEN = result;
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	public String getAccessTokenPublic(){
		String result= null;
		HttpClient client = new HttpClient();
		HttpMethod method=new GetMethod("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ConfigCache.getConfig("wx.mp.appId")+"&secret="+ConfigCache.getConfig("wx.mp.secret"));
		try {
			client.executeMethod(method);
			result = method.getResponseBodyAsString();
			method.releaseConnection();

			JSONObject jsonob = JSONObject.fromObject(result);
			result = jsonob.getString("access_token");
			ACCESS_TOKEN = result;
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 
	 * @param code
	 * @return
	 */
	public WxUserJson getUserAccessTokenByCode(String code){
		String result= null;
		WxUserJson wxuser = new WxUserJson();
		HttpClient client = new HttpClient();
		String resultStr = String.format(this.USERACCESSTOKEN_URL,ConfigCache.getConfig("wx.ma.appId"),ConfigCache.getConfig("wx.ma.secret"));
		HttpMethod method=new GetMethod(resultStr.replace("CODE", code));
		try {
			client.executeMethod(method);
			result = method.getResponseBodyAsString();
			method.releaseConnection();
			
			Gson gs = new Gson();
			wxuser = gs.fromJson(result, WxUserJson.class);
			
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return wxuser;
	}

	/**
	 *
	 * @param code
	 * @return
	 */
	public WxUserJson getAppletAccessTokenByCode(String code){
		String result= null;
		WxUserJson wxuser = new WxUserJson();
		HttpClient client = new HttpClient();
		String resultStr = String.format(this.APPLETACCESSTOKEN_URL,ConfigCache.getConfig("wx.ma.appId"),ConfigCache.getConfig("wx.ma.secret"));
		HttpMethod method=new GetMethod(resultStr.replace("CODE", code));
		try {
			client.executeMethod(method);
			result = method.getResponseBodyAsString();
			method.releaseConnection();

			Gson gs = new Gson();
			wxuser = gs.fromJson(result, WxUserJson.class);

		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return wxuser;
	}

	
	public String getJsApiTocket(){
		String result = "";
		HttpClient client = new HttpClient();
		String requestUrl = this.JSAPI_URL;
		HttpMethod method=new GetMethod(requestUrl.replace("ACCESS_TOKEN", this.ACCESS_TOKEN));
		try {
			client.executeMethod(method);
			result = method.getResponseBodyAsString();
			method.releaseConnection();
			
			JSONObject jsonob = JSONObject.fromObject(result);
			result = jsonob.getString("ticket");
			this.JSAPI_TICKET = result;
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 获取微信签名
	 * @param nonceStr 随机字符串
	 * @param timestamp 时间戳
	 * @param URL 跳转URL
	 * @return 签名字符串
	 */
	@SuppressWarnings("deprecation")
	public String getJsSignature(String nonceStr, long timestamp, String URL){
		String re = null;
		getWxAccessToken();
		getJsApiTocket();
		String str1 = JS_STR;
		String str = str1.replace("JSAPI_TICKET", JSAPI_TICKET).replace("NONCESTR", nonceStr).replace("TIMESTAMP", String.valueOf(timestamp)).replace("URL", URL);
		re = DigestUtils.shaHex(str);
		return re;
	}


	/**
	 * 获取微信公共号AccessToken，并存贮于静态变量ACCESS_TOKEN
	 * @return
	 */
	@SuppressWarnings("static-access")
	public String getWxAccessToken(){
		String result= null;
		HttpClient client = new HttpClient();
		HttpMethod method=new GetMethod(String.format(ACCESSTOKEN_URL_FOR_PUBLIC, ConfigCache.getConfig("wx.mp.appId"),ConfigCache.getConfig("wx.mp.secret")));
		try {
			client.executeMethod(method);
			result = method.getResponseBodyAsString();
			method.releaseConnection();

			JSONObject jsonob = JSONObject.fromObject(result);
			result = jsonob.getString("access_token");
			System.out.println("this is share access:"+result);
			ACCESS_TOKEN = result;
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获取用户信息
	 * @param openid
	 * @return
	 */
	public WxUserJson getUserInfos(String openid,String access_token) {
		String result= null;
		WxUserJson wxuser = new WxUserJson();
		HttpClient client = new HttpClient();
		String resultStr = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
		HttpMethod method=new GetMethod(resultStr);
		try {
			client.executeMethod(method);
			result = method.getResponseBodyAsString();
			method.releaseConnection();
			
			Gson gs = new Gson();
			wxuser = gs.fromJson(new String(result.getBytes(), StandardCharsets.UTF_8), WxUserJson.class);
			
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return wxuser;
	}


//	public String downAndSaveMedia(String mediaId){
//		String  ffile = DateUtil.getDays(), fileName = "";
//		String filePath = PathUtil.getClasspath() + Const.FILEPATHIMG + ffile;		//文件上传路径
////		fileName = FileUpload.fileUp(file, filePath, this.get32UUID());				//执行上传
////		String filePath = WebUtil.getRootPath() + File.separator + "uploadImg" + File.separator;
////		String imgPath = WxBaseServiceImpl.class.getClassLoader().getResource("").getPath();
////        imgPath = imgPath.split("WEB-INF")[0];
////        imgPath = imgPath+"uploadImg/";
//	    // 拼接请求地址
//	    String requestUrl = this.DOWNMEDIA_URL;
//	    requestUrl = requestUrl.replace("ACCESS_TOKEN", this.ACCESS_TOKEN).replace("MEDIA_ID", mediaId);
//	    System.out.println(requestUrl);
//	    try {
//	      URL url = new URL(requestUrl);
//	      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//	      conn.setDoInput(true);
//	      conn.setRequestMethod("GET");
//
////	      if (!this.FILEDIR.endsWith("/")) {
////	      }
//	      // 根据内容类型获取扩展名
//	      String fileExt = WeixinUtil.getFileEndWitsh(conn.getHeaderField("Content-Type"));
//	      // 将mediaId作为文件名
//	      fileName = mediaId + fileExt;
//	      filePath = filePath + fileName;
//
//	      BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
//	      File f = new File(filePath);
//	      System.out.println(f.canWrite()+"------------------------");
//	      FileOutputStream fos = new FileOutputStream(f);
//	      byte[] buf = new byte[8096];
//	      int size = 0;
//	      while ((size = bis.read(buf)) != -1)
//	        fos.write(buf, 0, size);
//	      fos.close();
//	      bis.close();
//
//	      conn.disconnect();
//	      String info = String.format("下载媒体文件成功，filePath=" + filePath);
//	      System.out.println(info);
//	    } catch (Exception e) {
//	      fileName = null;
//	      String error = String.format("下载媒体文件失败：%s", e);
//	      System.out.println(error);
//	    }
//	    return ffile + fileName;
//	}
	
}
